import { Sprite, SpriteFrame,Node, Label, Button } from "cc";
import { instantiate, Prefab } from "cc";
import { _decorator } from "cc";
import { NPrefab } from "../../ngame/sync/state/NSyncStateServer";
import UIView from "../../ngame/ui/UIView";
import loader from "../../ngame/util/loader";
import { JGet } from "../axios";
import { PlayerGoods, Synth } from "../entitys/EntityConst";
import { GetPlayerGoodsAPI, GetSynthListAPI, SynthGoodsAPI } from "../GameAPI";
import GameConst, { NPrefabConst, NPrefabKeys, SynthInfo, Synths, UIConfig, UI_VIEW } from "../GameConst";
const { ccclass, property,executeInEditMode } = _decorator;

@ccclass("UIBackPack")
export default class UIBackPack extends UIView{

    @property(Prefab)
    itemPrefab:Prefab;

    @property(Prefab)
    itemSynthPrefab:Prefab;

    @property(Node)
    content:Node;

    @property(Node)
    contentSynth:Node;

    @property([Node])
    rightContents:Node[] = [];

    async nInitView(){
        
        this.rightContents.forEach(node => {
            node.active = false;
        })

        await this.query();

    }

    //点击右边显示
    onOpenRightShow(e,data){

        this.rightContents.forEach(node => {
            node.active = false;
        })

        this.rightContents[parseInt(data)].active = true;

        this.query().then();

    }

    async query(){
        
        //获取玩家道具
        let goods:PlayerGoods[] = await GetPlayerGoodsAPI();

        this.content.destroyAllChildren();
        this.contentSynth.destroyAllChildren();

        for (let index = 0; index < goods.length; index++) {
            const data = goods[index];

            let item = instantiate(this.itemPrefab);
            let nPrefab:NPrefab = NPrefabConst[data.goodsId];
            let image = await loader.loadlocal<SpriteFrame>(nPrefab.image);
            item.getComponentInChildren(Sprite).spriteFrame = image.clone();
            item.getComponentInChildren(Label).string = `${data.goodsNum}`;
            item.parent = this.content;

        }

        //获取合成道具
        let synths:Synth[] = await GetSynthListAPI();
        for (let index = 0; index < synths.length; index++) {
            const data = synths[index];
            
            let item = instantiate(this.itemSynthPrefab);
            let nPrefab:NPrefab = NPrefabConst[data.synthResult];
            let image = await loader.loadlocal<SpriteFrame>(nPrefab.image);
            item.getComponentInChildren(Sprite).spriteFrame = image.clone();
            item.on(Button.EventType.CLICK,() => {
                this.onClickSynth(data);
            },this);
            item.parent = this.contentSynth;
        }

    }

    //点击制作
    async onClickSynth(synth:Synth){

        if(await SynthGoodsAPI(synth.synthId)){
            UI_VIEW.POPUP.show(UIConfig.Tips,"合成成功");
        }else{
            UI_VIEW.POPUP.show(UIConfig.Tips,"合成失败");
        }

    }

}

